package com.frxuexi.shop.view

import android.util.Log
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.ShopBeanItem
import com.frxuexi.lib_base.mvi.BaseFragment
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.shop.intent.ShopIntent
import com.frxuexi.shop.viewmodel.ShopViewModel
import com.frxuexi.shop.adapter.OnItemClickListener
import com.frxuexi.shop.adapter.OnItemLongClickListener
import com.frxuexi.shop.adapter.ShopAdapter
import com.frxuexi.shop.databinding.FragmentShopBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class ShopFragment : BaseFragment<FragmentShopBinding, ShopIntent, ShopViewModel>() {
    override val binding: FragmentShopBinding by lazy { FragmentShopBinding.inflate(layoutInflater) }
    override val vm: ShopViewModel by viewModels<ShopViewModel>()
    val shopAdapter by lazy { ShopAdapter() }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        Log.i("lr",it.data.toString())
                        shopAdapter.submitData(it.data as PagingData<ShopBeanItem>)
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        binding.rvShop.apply {
            adapter=shopAdapter
            layoutManager= StaggeredGridLayoutManager(2, RecyclerView.VERTICAL)
        }
        vm.sendIntent(ShopIntent.getShops(1, 1))

        shopAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(position: Int, item: ShopBeanItem) {
               ArouterManager.nav(requireContext(),"/shop/ShopActivity",item.id)
            }
        })

        shopAdapter.setOnItemLongClickListener(object : OnItemLongClickListener {
            override fun onItemLongClick(position: Int): Boolean {
                ToastUtils.showLong(position.toString())
                return true
            }
        })
    }

}